
if(length(tryCatch(list.dirs(path="~/Library/CloudStorage/Dropbox/Robots and Trade in Services"),error=function(e) e))==0){
  base.path<-"~/Dropbox/Robots and Trade in Services/"
} else {
  base.path<-"~/Library/CloudStorage/Dropbox/Robots and Trade in Services/"
}

#Load data and functions
source(paste0(base.path,"Drafts/Replication/03 Functions and Processing.R"))

#############
## Table 1 ##
#############

labor.subsample<-plotter(subsample="Labor",depvar="restrict_imports_difference",return_df = TRUE) %>% select(val_mean,relevant_outcome=restrict_imports_difference,treatment_foreign_domestic,treatment_automation_labor,relevant_policy=restrict_imports,transfers=benefits_to_unemployed)

automation.subsample<-plotter(subsample="Automation",depvar="restrict_automation_difference",return_df = TRUE) %>% select(val_mean,relevant_outcome=restrict_automation_difference,treatment_foreign_domestic,treatment_automation_labor,relevant_policy=restrict_automation,transfers=benefits_to_unemployed)


bind_rows(labor.subsample,automation.subsample) %>%
  group_by(treatment_automation_labor,treatment_foreign_domestic) %>%
  summarize(val_mean=mean(relevant_outcome,na.rm=TRUE),
            val_var=var(relevant_outcome,na.rm=TRUE),
            policy_mean=mean(relevant_policy,na.rm=TRUE),
            transfers_mean=mean(transfers,na.rm=TRUE),
            num=n()
  ) %>%
  ungroup() %>% 
  mutate(se=sqrt(val_var/num)) %>%
  mutate(contents=paste0("\\makecell{\\\\ \\footnotesize Backpedaling Policy: $", round(policy_mean,1),"$ \\\\ \\footnotesize Transfers: $",round(transfers_mean,1),"$ \\\\ \\\\ \\normalsize \\textbf{Difference: $",round(val_mean,1),"$} \\\\ \\footnotesize 95\\% Conf. Int. $[",round(val_mean-qnorm(0.975)*se,1),", ",round(val_mean+qnorm(0.975)*se,1),"]$ }")) %>% 
  mutate(treatment_foreign_domestic=factor(treatment_foreign_domestic,levels=c("Foreign","Domestic"))) %>%
  reshape2::dcast(treatment_foreign_domestic ~ treatment_automation_labor,value.var="contents") %>%
  tibble::add_row(treatment_foreign_domestic="",Labor="\\makecell{\\textbf{Labor} \\\\ (Imported)} ",Automation="\\makecell{\\textbf{Automation} \\\\ (Exported)}",.before=1) %>%
  mutate(treatment_foreign_domestic=paste0("\\textbf{",treatment_foreign_domestic,"}")) %>%
  xtable::xtable(digits=2,label="tab:diffs",caption="Mean differences in preferred policy response by treatment condition. All entries are means of support for the relevant policy, transfers, or their difference as appropriate. Reported differences may not agree with reported levels due to rounding.",align=c("|c|c|c|c|")) %>%
  xtable::print.xtable(comment = FALSE,include.rownames = FALSE,include.colnames = FALSE,sanitize.text.function = function(x) x,hline.after=c(0,1,2,3))

